package core;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import core.util.IoUtils;

@SuppressWarnings("serial")
public class FileDownloadServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    super.doGet(req, resp);
    String path = req.getParameter("file");
    download(path,req, resp);
  }
  
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
      IOException {
    doGet(req, resp);
  }
  
  @Override
  public void init() throws ServletException {
    super.init();
  }
  
  @SuppressWarnings("deprecation")
  public HttpServletResponse download(String path,HttpServletRequest request, HttpServletResponse response) {
	  InputStream fis=null;
	  OutputStream toClient=null;
      try {
          // path是指欲下载的文件的路径。
          File file = new File(path);
          // 取得文件名。
          String filename = file.getName();
          // 取得文件的后缀名。
          // 以流的形式下载文件。
          fis = new BufferedInputStream(new FileInputStream(file));
          byte[] buffer = new byte[fis.available()];
          fis.read(buffer);
          // 清空response
          response.reset();
          // 设置response的Header
          response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("utf-8"),"ISO-8859-1"));
          response.addHeader("Content-Length", "" + file.length());
          toClient = new BufferedOutputStream(response.getOutputStream());
          response.setContentType("application/octet-stream");
          toClient.write(buffer);
          toClient.flush();   
      } catch (IOException ex) {
          ex.printStackTrace();
      }finally{
    	  IoUtils.close(toClient);
    	  IoUtils.close(fis);
      }
      return response;
  }
}
